import axios from 'axios'

/**
 * 代币信息服务
 */
export class TokenService {
  /**
   * 从Binance API获取代币信息
   * @param {string} contractAddress - 合约地址
   * @param {number} chainId - 链ID，默认56 (BSC)
   * @returns {Promise<Object>} 代币信息
   */
  static async getTokenInfo(contractAddress, chainId = 56) {
    if (!contractAddress) {
      throw new Error('合约地址不能为空')
    }

    // 验证合约地址格式
    if (!/^0x[a-fA-F0-9]{40}$/.test(contractAddress)) {
      throw new Error('合约地址格式不正确')
    }

    try {
      const url = 'https://www.binance.com/bapi/defi/v1/public/wallet-direct/buw/wallet/cex/alpha/token/full/info'
      const params = {
        chainId: chainId,
        contractAddress: contractAddress
      }

      const response = await axios.get(url, {
        params,
        timeout: 10000,
        headers: {
          'Accept': 'application/json',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
      })

      const { data } = response.data

      if (!data || !data.metaInfo) {
        throw new Error('未找到代币信息')
      }

      const { metaInfo } = data

      return {
        alphaId: metaInfo.alphaId,
        name: metaInfo.name,
        symbol: metaInfo.symbol,
        contractAddress: metaInfo.contractAddress,
        chainId: metaInfo.chainId,
        decimals: metaInfo.decimals,
        iconUrl: metaInfo.iconUrl,
        description: metaInfo.cnDescription || metaInfo.enDescription || '',
        website: metaInfo.links?.find(link => link.label === 'website')?.link || '',
        telegram: metaInfo.socialMedias?.find(social => social.label === 'telegram')?.link || '',
        twitter: metaInfo.socialMedias?.find(social => social.label === 'x')?.link || ''
      }
    } catch (error) {
      console.error('获取代币信息失败:', error)

      if (error.response) {
        const status = error.response.status
        if (status === 404) {
          throw new Error('未找到该合约地址的代币信息')
        } else if (status === 429) {
          throw new Error('请求过于频繁，请稍后再试')
        } else {
          throw new Error(`API请求失败 (${status})`)
        }
      } else if (error.code === 'ECONNABORTED') {
        throw new Error('请求超时，请检查网络连接')
      } else if (error.message) {
        throw new Error(error.message)
      } else {
        throw new Error('获取代币信息失败，请稍后再试')
      }
    }
  }

  /**
   * 根据代币信息生成基础资产代码
   * @param {Object} tokenInfo - 代币信息
   * @returns {string} 基础资产代码
   */
  static generateBaseAsset(tokenInfo) {
    if (tokenInfo.alphaId) {
      return tokenInfo.alphaId
    }
    // 如果没有alphaId，使用symbol作为fallback
    return tokenInfo.symbol || 'TOKEN'
  }
}

export default TokenService